<template>
  <div class="filter">
    <t-dialog
      width="1166px"
      :visible.sync="visible"
      :closeBtn="false"
      placement="center"
      :show-overlay="false"
      :close-on-overlay-click="false"
    >
      <template #header>
        <div class="flex align-center justify-between" style="width: 100%;">
          <div class="drawer-head" @click="close">
            <p class="chevron-left">
              <icon-font name="chevron-left" size="18px" />
            </p>
            <h3>{{header}}</h3>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="footer-btn">
          <t-space size="22px">
            <div class="head-hint">
              <p>数量：</p><p>{{ product_data.length }}</p>
            </div>
            <!--<div class="head-hint">-->
            <!--  <p>金额：</p>-->
            <!--  <p>¥{{ totalPrice }}</p>-->
            <!--</div>-->
          </t-space>
          <t-space size="8px">
            <t-button theme="primary" class="" @click="handleSubmit">
              <!--<icon-font name="check" size="22px" class="mr12" />-->
              选好了
            </t-button>
            <t-button theme="default" class="" @click="close">取消</t-button>
          </t-space>
        </div>
      </template>
      <div class="content mt16">
        <div class="classify">
          <t-tree :data="items" :actived="[params.product_classify_id]" :keys="{label: 'label', value: 'value'}" activable hover transition expandParent expandOnClickNode @click="classifyClick" />
        </div>
        <div style="width: 100%;">
          <div class="filter flex align-center justify-between" style="margin-top: 0; padding-top: 0">
            <t-space size="12px">
              <t-input style="width: 220px;" v-model="params.key" placeholder="搜索产品" @change="getList">
                <template #label>
                  <icon-font name="search" size="16px" style="color:#000;font-weight: bold"/>
                </template>
              </t-input>
            </t-space>
            <add-product-pop :classifyOptions="classifyOptions" @change="getList"></add-product-pop>
          </div>
          <div class="pt16">
            <t-table
              rowKey="id"
              :data="lists"
              :columns="columns"
              :stripe="stripe"
              :bordered="bordered"
              :hover="hover"
              :size="size"
              :max-height="maxHeight"
              :table-layout="tableLayout ? 'auto' : 'fixed'"
              :showHeader="showHeader"
              cellEmptyContent="-"
              resizable
              :loading="loading"
              :selected-row-keys="selectedRowKeys"
              @select-change="handleSelectChange"
            >
              <template #select="{row}">
                <t-checkbox :checked="selectedRowKeys.includes(row.id)" :disabled="row.quantity <= 0" :value="row.id" @change="changeRowKeys($event,row)" />
              </template>
              <template #product_thumb="{row}">
                <t-image-viewer v-if="row.product_thumb" :images="[row.product_thumb]" :closeOnEscKeydown="false">
                  <template #trigger="{ open }">
                    <div class="tdesign-demo-image-viewer__ui-image" @click="open">
                      <p class="prod-img">
                        <img alt="图片" :src="row.product_thumb" />
                      </p>
                      <div class="tdesign-demo-image-viewer__ui-image--hover">
                        <span><browse-icon size="1.4em"/> </span>
                      </div>
                    </div>
                  </template>
                </t-image-viewer>
                <p v-else>-</p>
              </template>
              <template #info="{row}">
                <div style="display: flex;flex-wrap: wrap;gap: 8px;">
                  <t-tag v-if="row.out_quantity" theme="success" variant="outline">
                    数量: {{ row.out_quantity }}
                  </t-tag>
                </div>
              </template>
            </t-table>
          </div>
        </div>
      </div>
    </t-dialog>

    <!-- 填写信息 -->
    <config-info ref="config" @cancel="handleCanel" @confirm="handleConfirm"></config-info>
  </div>
</template>

<script>
import { IconFont, BrowseIcon } from "tdesign-icons-vue";
import {classifyListApi} from "@/api/classify";
import {warehouse_product_stockListApi} from "@/api/warehouseInventory";
import ConfigInfo from "@/pages/warehouse/components/product-outbound/config-info.vue";
import AddProductPop from "@/pages/warehouse/components/add-product-pop.vue";

export default {
  name: 'ProductAdd',
  props: {
    warehouseId: {
      type: [String, Number],
      default: ''
    }
  },
  components: {
    AddProductPop,
    ConfigInfo,
    IconFont,
    BrowseIcon,
  },
  data() {
    return {
      visible: false,
      header: '选择出库产品',
      confirmBtn: {
        text: '保存',
        theme: 'primary',
        loading: false
      },

      params: {
        page: 1,  // 当前页
        limit: 9999,  // 每页条数
        warehouse_id: '', // 仓库ID
        product_id: '', // 产品ID
        product_classify_id: '', // 产品分类ID
        key: '',  // 关键字
        status: '', // 状态
      },

      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        {colKey: 'select', title: '选择', align: 'center', width: 70,},
        {colKey: 'id', title: 'ID', width: 60},
        {colKey: 'product_thumb', title: '图片', align: 'center', width: 70,},
        {colKey: 'product_title', title: '产品名称', ellipsis: true},
        {colKey: 'sn', title: 'SN', width: 240},
        {colKey: 'quantity', title: '库存数', width: 80},
        {colKey: 'info', title: '当前出库信息', width: 120},
      ],
      selectedRowKeys: [],
      product_data: [],
      totalPrice: '0.00',

      maxHeight: 420,
      loading: false,

      items: [],

      classifyOptions: []
    }
  },
  methods: {
    // 选中产品
    changeRowKeys(event, row) {
      if (this.selectedRowKeys.includes(row.id)) {
        let data = this.product_data.find(item => item.product_id === row.id)
        const item = Object.assign({}, row, data)
        this.$refs.config.open('again', item);
      } else {
        this.$refs.config.open('first', row);
      }
    },
    handleConfirm(row) {
      if (this.selectedRowKeys.includes(row.id)) {
        let index = this.product_data.findIndex(item => item.product_id === row.id)
        this.product_data[index] = row
      } else {
        this.selectedRowKeys.push(row.id)
        this.product_data.push(row)
      }

      let index = this.lists.findIndex(item => item.id === row.id);
      if (index !== -1) {
        this.lists[index].unit_price = row.unit_price
        this.lists[index].out_quantity = row.quantity
      }

      console.log('lists', this.lists)
      console.log('product_data', this.product_data)

      //this.lists[index].total_price = (row.unit_price * row.quantity).toFixed(2)
      //this.totalPrice = this.product_data.reduce((total, item) => total + item.unit_price * item.quantity, 0).toFixed(2)
    },
    handleCanel(row) {
      this.selectedRowKeys = this.selectedRowKeys.filter(item => item !== row.id)
      this.product_data = this.product_data.filter(item => item.id !== row.id)
      let index = this.lists.findIndex(item => item.id === row.product_id);
      this.lists[index].quantity = 0
      //this.totalPrice = this.product_data.reduce((total, item) => total + item.unit_price * item.quantity, 0).toFixed(2)
    },
    // 切换分类
    classifyClick(value) {
      //if (!value.node.data.children.length) {
      this.params.product_classify_id = value.node.value
      this.getList()
      //}
    },
    handleSelectChange(value, {selectedRowData}) {
      this.selectedRowKeys = value;
    },
    // 提交
    handleSubmit() {
      if (!this.product_data.length) {
        this.$message.error('请选择产品')
        return
      }
      const lists = this.product_data.map(item=> ({
        id: item.id,
        title: item.title,
        product_id: item.product_id, // 产品ID
        unit_id: item.unit_id,  // 单位ID
        unit_title: item.unit_title,  // 单位ID
        quantity: item.quantity, // 数量两位小数
        max_quantity: item.max_quantity, // 数量两位小数
        is_sn: item.is_sn,
        sn: item.sn,
        unit_price: item.unit_price,
        remark: item.remark,
      }))


      this.$emit('confirm', lists)
      this.close()
    },
    // 获取列表
    getList() {
      this.loading = true
      warehouse_product_stockListApi({...this.params, product_classify_id: this.params.product_classify_id !== '0' ? this.params.product_classify_id : ''}).then(res => {
        //this.lists = res.data
        this.lists = res.data.map(item=> ({ ...item, out_quantity: '' }))
      }).catch(err => {
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取分类列表
    getClassifyList() {
      const params = {
        page: 1,
        limit: 9999,
        belong_module: 'product_classify',
      }
      classifyListApi(params).then(res=> {
        let lists = res.data.map(item=> {
          return {
            label: item.title,
            value: item.id,
            id: item.id,
            pid: item.pid,
          }
        })
        this.classifyOptions = this.buildHierarchyRecursive(lists)

        const hierarchy = this.buildHierarchyRecursive(lists)
        const items = [{label: '全部', value: '0', id: '0', pid: '0', expanded:true, children: hierarchy}]
        this.items = items
      })
    },
    buildHierarchyRecursive(data, pid = 0) {
      return data
        .filter(item => item.pid === pid)
        .map(item => ({
          ...item,
          children: this.buildHierarchyRecursive(data, item.id)
        }));
    },
    open() {
      this.lists = []
      this.visible = true
      this.product_data = []
      this.selectedRowKeys = []
      this.params.warehouse_id = this.warehouseId
      this.getList()
      this.getClassifyList()
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>

.head-hint {
  display: flex;
  align-items: center;

  font-size: 20px;
  font-weight: 400;
  line-height: 19.6px;
  text-align: left;

  p:first-child {
    color: var(--td-font-gray-2);
  }
}

.content {
  height: 60vh;
  display: flex;
  gap: 12px;

  /deep/ .classify {
    width: 247px;
    padding: 18px;
    flex-shrink: 0;
    overflow-x: hidden;
    overflow-y: auto;
    max-height: 100%;
    box-sizing: border-box;
    border: 1px solid #E5E5E5;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      border: 0px solid transparent;
      background-clip: content-box;
      background-color: var(--td-scrollbar-color);
      border-radius: 11px;
    }

    .t-is-active .t-tree__label {
      color: var(--td-brand-color);
    }
  }


  /deep/ .filter {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .t-input, .t-input.t-is-readonly {
      background-color: #F8F8F8;
    }
  }
}

.add-btn-wrap {
  padding-top: 24px;
  border-top: 1px solid #E1E1E1;
}

/deep/ .t-dialog__footer {
  height: 75px;
}

.footer-btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  width: 100%;
  padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xxl);
  background-color: #F9F9F9;
  border-bottom: 1px solid #F9F9F9;

  display: flex;
  align-items: center;
  justify-content: space-between;
}

.confirm-btn {
  width: 190px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  border-radius: var(--td-radius-medium);
}

.cancel-btn {
  width: 82px;
  height: 42px;
  color: #FFFFFF;
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  background-color: #B8B8B8;
  border-radius: var(--td-radius-medium);
}
</style>
